package entity.lianxi.demo07;

import java.lang.reflect.Array;
import java.lang.reflect.Field;

public class MainTest {
    public static void main(String[] args) throws Exception {
        // 创建一个用于存储 Student 对象的一维数组，一共存储两个元素
        Object arr = Array.newInstance(Student.class, 2);

        // 获取操作类的 Class 对象
        Class<Student> clazz = Student.class;

        // Constructor<Student> constructor = clazz.getConstructor();
        // Student stu = constructor.newInstance();

        // 基于默认构造方法实例化对象
        Student stu1 = clazz.getConstructor().newInstance();

        // 获取 Student 类的 Field 对象
        Field nameField = clazz.getDeclaredField("name");
        Field ageField = clazz.getDeclaredField("age");
        Field weightField = clazz.getDeclaredField("weight");

        // 开启私有成员的访问权限
        nameField.setAccessible(true);
        ageField.setAccessible(true);
        weightField.setAccessible(true);

        // 调用 setter 方法，实初化对象
        nameField.set(stu1, "张三");
        ageField.set(stu1, 18);
        weightField.set(stu1, 65.5);

        // Student(String name,int age,Double score)
        Student stu2 = clazz
                .getConstructor(String.class, int.class, Double.class)
                .newInstance("李四", 20, 70.0);

        // 向数组添加元素
        Array.set(arr,0,stu1);
        Array.set(arr,1,stu2);

        // 循环遍历数组
        // if(arr instanceof Student[]) {
        //     Student[] stuArr = (Student[])arr ;
        //     for (Student stu : stuArr) {
        //         System.out.println(stu);
        //     }
        // }

        for (int i = 0; i < Array.getLength(arr); i++) {
            Object stu = Array.get(arr, i);
            System.out.println(stu);
        }
    }
}
